package fm.dongman.modellib.source

import android.util.Log
import fm.dongman.animefm.contractlib.BaseDataSource
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicClassifyContract
import fm.dongman.animefm.contractlib.model.ClassifyDataModel
import fm.dongman.animefm.contractlib.model.ClassifyDataModel.*
import fm.dongman.modellib.RemoteHelper
import fm.dongman.modellib.StaticArea.StaticUrl
import fm.dongman.modellib.remote.RemoteOperationHelper
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * 新番分类数据源
 * Created by shize on 2017/10/28.
 */
class ComicClassifyRepository private constructor() : ComicClassifyContract.IComicClassifyDataSource {
    override fun getData(callback: BaseDataSource.LoadSourceCallback<ClassifyDataModel>) {
        val jsonObj = RemoteHelper.instance.parseGetUrl(StaticUrl.COMIC_CLASSIFY_REMOTE)
        if (jsonObj == null) {
            callback.onDataLoadFiled()
            return
        }
        callback.onDataLoaded(downClassifyData(jsonObj))
    }

    override fun getComicList(page: Int, filter: ClassifyDataModel.ClassifyFilter,
                              callback: BaseDataSource.LoadSourceCallback<List<IModel.IComicModel>>) {
        val jsonObj = RemoteHelper.instance.parseGetUrl(getGetUrl(
                arrayOf(CLASSIFY_GENRE, CLASSIFY_ORDER, CLASSIFY_PAGE, CLASSIFY_SIZE,
                        CLASSIFY_COUNTRY, CLASSIFY_STATE, CLASSIFY_TIME, CLASSIFY_MODE),
                arrayOf(filter.type, filter.order.toString(), page.toString(), filter.count.toString(),
                        filter.country, filter.state, filter.time, filter.size)))
        if (jsonObj == null) {
            callback.onDataLoadFiled()
            return
        }
        callback.onDataLoaded(downClassifyComics(jsonObj))
    }

    /**
     * 获取 GET 请求地址
     * @param keys 参数名
     * @param values 参数值
     * @return 请求地址
     */
    private fun getGetUrl(keys: Array<String>, values: Array<String>): String {
        var url = StaticUrl.COMIC_CLASSIFY_REMOTE_POST
        (0 until keys.size).forEach {
            if (values[it] == "") {
                return@forEach
            }
            url += keys[it] + "=" + values[it] + "&"
        }
        url = url.substring(0 until url.lastIndex)
        Log.d(javaClass.simpleName, "分类 GET 请求地址：" + url)
        return url
    }

    /**
     * 解析分类数据
     * @param json json 对象
     * @return 类型数据
     */
    private fun downClassifyData(json: JSONObject): ClassifyDataModel {
        val jsonObj: JSONObject?
        val model = ClassifyDataModel()
        // 添加一个“全部”默认选项
        addDefaultItem(model)
        try {
            jsonObj = json.getJSONObject("data")
            // 解析国家
            var array = jsonObj.getJSONArray(CLASSIFY_COUNTRY)
            (0 until array.length()).forEach {
                model.countries.add(parseTypeData(array, it))
            }
            // 解析类型
            array = jsonObj.getJSONArray(CLASSIFY_GENRE)
            (0 until array.length()).forEach {
                model.type.add(parseTypeData(array, it))
            }
            // 解析篇幅
            array = jsonObj.getJSONArray(CLASSIFY_MODE)
            (0 until array.length()).forEach {
                model.size.add(parseTypeData(array, it))
            }
            // 解析时间
            array = jsonObj.getJSONArray(CLASSIFY_TIME)
            (0 until array.length()).forEach {
                model.time.add(parseTypeData(array, it))
            }
            // 解析状态
            array = jsonObj.getJSONArray(CLASSIFY_STATE)
            (0 until array.length()).forEach {
                model.state.add(parseTypeData(array, it))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return model
    }

    /**
     * 添加默认“全部”选项
     * @param model 分类模型
     */
    private fun addDefaultItem(model: ClassifyDataModel) {
        model.countries.add(TypeData())
        model.type.add(TypeData())
        model.size.add(TypeData())
        model.time.add(TypeData())
        model.state.add(TypeData())
    }

    /**
     * 解析类型数据
     * @param array 类型数组
     * @param it 数组序号
     */
    private fun parseTypeData(array: JSONArray, it: Int) =
            TypeData(array.getJSONObject(it).optString(PARAM_ID),
                    array.getJSONObject(it).optString(PARAM_NAME))


    /**
     * 通过分类获取番剧
     * @param jsonObject json 对象
     * @return 对应番剧集合
     */
    private fun downClassifyComics(jsonObject: JSONObject): List<IModel.IComicModel> {
        val comics: ArrayList<IModel.IComicModel> = ArrayList()
        try {
            val array = jsonObject.getJSONObject("data").getJSONArray(CLASSIFY_LIST)
            (0 until array.length()).forEach {
                comics.add(RemoteOperationHelper.getOperationHelper().parseComicModel(array.getJSONObject(it)))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return comics
    }

    override fun refreshData() {}

    override fun saveData(dataModel: ClassifyDataModel) {}

    override fun offLine() {}

    companion object {
        val PARAM_ID = "id" // 分类参数 id
        val PARAM_NAME = "name" // 分类参数 name
        /*获取类型参数*/
        val CLASSIFY_COUNTRY = "country" // 国家
        val CLASSIFY_GENRE = "genre" // 类型
        val CLASSIFY_MODE = "mode" // 篇幅
        val CLASSIFY_TIME = "publishTime" // 时间
        val CLASSIFY_STATE = "state" // 状态
        val CLASSIFY_ORDER = "order" // 排序
        val CLASSIFY_PAGE = "page" // 页数
        val CLASSIFY_SIZE = "size" // 每页数据个数
        /*获取番剧参数*/
        val CLASSIFY_LIST = "list" // 番剧列表

        private var INSTANCE: ComicClassifyRepository? = null // 实例对象

        /**
         * 获取新番分类数据源
         */
        fun getInstance(): ComicClassifyRepository {
            if (INSTANCE == null) {
                INSTANCE = ComicClassifyRepository()
            }
            return INSTANCE!!
        }
    }
}